<template>
	<view class="layout">
		<view class="input-display">
			<view class="text" style="color: aliceblue;">
				{{inputValue}}	
			</view>
		</view>
		<view class="btn-group">
			<view v-for="(item,index) in btnsData" :key="index" :style="`background: ${item.bgcolor};color:#fff`" class="btnshap btn" @tap="btnHandler(item)">
				<view class="text">
					{{item.text}}
				</view>
			</view>	
		</view>
		<view>
			<!-- 输入框示例 -->
			<uni-popup ref="inputDialog" type="dialog">
				<uni-popup-dialog ref="inputClose"  mode="input" title="保存公式" :value="getname"
					placeholder="请填写公式名称" @confirm="dialogInputConfirm"></uni-popup-dialog>
			</uni-popup>
		</view>
	</view>
</template>

<script>
	import CustomInputDialog from './CustomInputDialog.vue';
	import {setFormula} from '@/common/api'
	import * as util from '@/common/util.js';
	
	export default {
		components: {
			CustomInputDialog
		},
		data() {
			return {
				isDialogVisible: false,
				btnsData:[
					{bgcolor: '#B0B0B0', text: '长', value: 'length'},
					{bgcolor: '#353535', text: '7', value: '7'},
					{bgcolor: '#353535', text: '8', value: '8'},
					{bgcolor: '#353535', text: '9', value: '9'},
					{bgcolor: '#FEA748', text: '+', value: '+'},
					{bgcolor: '#B0B0B0', text: '宽', value: 'width'},
					{bgcolor: '#353535', text: '4', value: '4'},
					{bgcolor: '#353535', text: '5', value: '5'},
					{bgcolor: '#353535', text: '6', value: '6'},
					{bgcolor: '#FEA748', text: '-', value: '-'},
					{bgcolor: '#B0B0B0', text: '高', value: 'height'},
					{bgcolor: '#353535', text: '1', value: '1'},
					{bgcolor: '#353535', text: '2', value: '2'},
					{bgcolor: '#353535', text: '3', value: '3'},
					{bgcolor: '#FEA748', text: '×', value: '×'},
					{bgcolor: '#B0B0B0', text: '来价', value: 'price'},
					{bgcolor: '#353535', text: '.', value: '.'},
					{bgcolor: '#353535', text: '0', value: '0'},
					{bgcolor: '#353535', text: '删除', value: 'delete'},
					{bgcolor: '#FEA748', text: '÷', value: '÷'},
					{bgcolor: '#353535', text: '(', value: '('},
					{bgcolor: '#353535', text: ')', value: ')'},
					{bgcolor: '#B0B0B0', text: '保存', value: 'confirm'},
				],
				symbolMap: {
					'长': 'length',
					'宽': 'width',
					'高': 'height',
					'来价': 'price',
					'删除': 'delete',
					'保存': 'confirm',
				},
				inputValue: '',
				user_id:'',
				getname:'',
				editType:'',
				formula:'',
				formula_len:'',
				formula_degree:'',
				name:'',
				private_formula_id:0,
			};
		},
		onLoad(option) {
			// 获取单个参数值
			// let getformula = query.formula;
			
			// let getname = query.name;
			// console.log(getformula);
			
			let userInfo = uni.getStorageSync('userInfo');
			if(!userInfo){
				uni.showToast({
					title: '登录失效,重新登录',//标题 必填
					icon: 'none',//图标
				    mask: false,//是否显示透明蒙层，防止触摸穿透，默认：false
				    duration: 2000,//提示的延迟时间，单位毫秒，默认：1500
				});
				setTimeout(function () {
					uni.navigateTo({
						url: '/pages/login/login'
					});
				}, 2000);
			}
			userInfo = JSON.parse(userInfo);
			// this.userinfo = userInfo;
			this.user_id = userInfo.user_id;
			
			let formula = uni.getStorageSync('formula');
			formula = JSON.parse(formula);
			let newformula = [];
			formula.forEach((i,index)=>{
				let formulaArr = [];
				formulaArr.private_formula_id = i.private_formula_id;
				formulaArr.name = i.name;
				formulaArr.is_top = i.is_top;
				formulaArr.formula_len = util.strReplace(i.formula_len);
				formulaArr.formula_degree = util.strReplace(i.formula_degree);
				formulaArr.oldformula = i.formula;
				formulaArr.user_id = i.user_id;
				//字符替换
				var newformulastr = util.strReplace(i.formula);
				
				formulaArr.formula = newformulastr;
				
				// formulaArr.text = i.name;
				newformula.push(formulaArr);
			})
			// this.newformula = newformula;
			const item = newformula.find(item => item.private_formula_id == option.id);
			console.log(item,"item");
			if (option && option.id) {
				// console.log(option.formula_len);
				if(option.types){
					this.editType = option.types;
				}
				this.name = item.name;
				this.private_formula_id = parseInt(item.private_formula_id);
				this.formula = item.formula;
				this.formula_len = item.formula_len;
				this.formula_degree = item.formula_degree;
				// console.log('name', name)	 // name eagle
				if(option.types == 'length'){
					this.inputValue = item.formula_len;
				}else if(option.types == 'height'){
					this.inputValue = item.formula_degree;
				}else if(option.types == 'edit'){
					this.inputValue = item.formula;
				}else{
					this.inputValue = '';
				}
			}else{
				this.inputValue = '';
			}
			
			if(option && option.name){
				this.getname = option.name;
			}else{
				this.getname = '';
			}
			
			
			
		},	
		methods: {
			btnHandler(e) {
				// if (!this.valideCharacter(e.text)) return
				if (e.value == 'confirm') return this.doSubmit()
				if (e.value == 'delete') return this.inputValue = this.inputValue.slice(0,this.inputValue.length -1)
				this.inputValue += e.text
			},
			valideCharacter(val){
				if (!val) return
				let wordkey = ['长','宽','高','来价'];
				let wordIndex = null;
				let flag = true;
				// val.split('').map((e,i) => {
				// 	wordkey.includes(e) && wordIndex = i
				// 	if (wordkey.includes(e) && wordkey.includes(val[i+1])) flag = false	
				// })
				// this.inputValue.split('').map((e,i) => {
				// 	val == e && flag = false
				// 	wordkey.includes(e) && wordIndex = i
				// 	if (wordkey.includes(e) && wordkey.includes(val[i+1])) flag = false	
				// })
				if (wordkey.includes(val) && wordkey.includes(this.inputValue.slice(-1))) flag = false
				return flag
			},
			doSubmit() {
				if(this.inputValue == ''){
					uni.showToast({
						title: '请先填写公式',
						duration: 1000,//提示的延迟时间，单位毫秒，默认：1500
					});
					return;
				}
				var newstr = this.inputValue.replace(/宽/g,"width");
				newstr = newstr.replace(/长/g,"length");
				newstr = newstr.replace(/高/g,"height");
				newstr = newstr.replace(/利润率/g,"profit");
				newstr = newstr.replace(/来价/g,"price");
				// let repFormuld = util.restrReplace(this.inputValue);
				console.log(newstr);
				let checkFormula = util.validatedFunc(newstr);
				
				console.log(checkFormula);
				if(checkFormula != true){
					uni.showToast({
						title: checkFormula,
						duration: 1000,//提示的延迟时间，单位毫秒，默认：1500
					});
					return;
				}
				if(this.editType != '' && this.editType == 'length'){
					console.log(this.inputValue)
					let hash = 'acbcefg';
					let timestamp = Math.round(new Date().getTime() / 1000).toString();
					let formula = this.formula;
					formula = util.restrReplace(formula);
					
					let formula_len = this.inputValue;
					formula_len = util.restrReplace(formula_len);
					
					let formula_degree = this.formula_degree;
					formula_degree = util.restrReplace(formula_degree);
					
					let user_id = this.user_id;
					let is_top = 0;
					let private_formula_id = this.private_formula_id;
					
					let name = this.name;
					setFormula({
						formula:formula,
						user_id:user_id,
						is_top:is_top,
						private_formula_id:private_formula_id,
						formula_len:formula_len,
						formula_degree:formula_degree,
						name:name,
						hash:hash,
						timestamp:timestamp,
						}).then(res=>{
						console.log("sssssssssss");
						if(res.code == '200'){
							uni.showToast({
								title: "保存成功",
								 duration: 2000,//提示的延迟时间，单位毫秒，默认：1500
							})
							
							uni.setStorageSync('formula',JSON.stringify(res.data.private_formula));
							uni.$emit('back', 12)
							// 跳转回上一页
							setTimeout(function () {
								// 返回时传递数据
								uni.switchTab({
									url:'/pages/index/formulalist'
								});
								// uni.navigateBack({
								// 	delta: 1,
								// 	success: () => {
								// 	  uni.$emit('back', 12)
								// 	}
								// })
							}, 2000);
						}else{
							uni.showToast({
								title: res.msg,//标题 必填
								icon: 'none',//图标
							    mask: false,//是否显示透明蒙层，防止触摸穿透，默认：false
							    duration: 2000,//提示的延迟时间，单位毫秒，默认：1500
							});
							return
						}
					}).catch(
						(response) => {
							uni.showToast({
								title: "系统错误"+response.message,//标题 必填
								icon: 'none',//图标
							    mask: false,//是否显示透明蒙层，防止触摸穿透，默认：false
							    duration: 2000,//提示的延迟时间，单位毫秒，默认：1500
							});
						}
					)
				}else if(this.editType != '' && this.editType == 'height'){
					console.log(this.inputValue)
					let hash = 'acbcefg';
					let timestamp = Math.round(new Date().getTime() / 1000).toString();
				
					let formula = this.formula;
					formula = util.restrReplace(formula);
					
					let formula_len = this.formula_len;
					formula_len = util.restrReplace(formula_len);
					
					let formula_degree = this.inputValue;
					formula_degree = util.restrReplace(formula_degree);
					
					
					let user_id = this.user_id;
					let is_top = 0;
					let private_formula_id = this.private_formula_id;
					
					let name = this.name;
					setFormula({
						formula:formula,
						user_id:user_id,
						is_top:is_top,
						private_formula_id:private_formula_id,
						formula_len:formula_len,
						formula_degree:formula_degree,
						name:name,
						hash:hash,
						timestamp:timestamp,
						}).then(res=>{
						console.log("sssssssssss");
						if(res.code == '200'){
							uni.showToast({
								title: "保存成功",
								 duration: 2000,//提示的延迟时间，单位毫秒，默认：1500
							})
							
							uni.setStorageSync('formula',JSON.stringify(res.data.private_formula));
							// 触发自定义事件并传递参数给上一页
							uni.$emit('back', 12)
							// 跳转回上一页
							setTimeout(function () {
								// 返回时传递数据
								uni.switchTab({
									url:'/pages/index/formulalist'
								});
								// uni.navigateBack({
								// 	delta: 1,
								// 	success: () => {
								// 	  uni.$emit('back', 12)
								// 	}
								// })
							}, 2000);
						}else{
							uni.showToast({
								title: res.msg,//标题 必填
								icon: 'none',//图标
							    mask: false,//是否显示透明蒙层，防止触摸穿透，默认：false
							    duration: 2000,//提示的延迟时间，单位毫秒，默认：1500
							});
							return
						}
					}).catch(
						(response) => {
							uni.showToast({
								title: "系统错误"+response.message,//标题 必填
								icon: 'none',//图标
							    mask: false,//是否显示透明蒙层，防止触摸穿透，默认：false
							    duration: 2000,//提示的延迟时间，单位毫秒，默认：1500
							});
						}
					)
				}else{
					// this.isDialogVisible = true;
					this.$refs.inputDialog.open()
					// console.log(this.inputValue)
				}
				
			},
			handleConfirm(value) {
			  console.log('用户输入:', value);
			  // 处理确认事件
			},
			dialogInputConfirm(val) {
				console.log(this.inputValue)
				let hash = 'acbcefg';
				let timestamp = Math.round(new Date().getTime() / 1000).toString();
				if(val == '' || val == null){
					uni.showToast({
						title: "公式名称不能为空",
						duration: 1000,//提示的延迟时间，单位毫秒，默认：1500
					});
					return;
				}
				let formula = this.inputValue;
				
				formula = util.restrReplace(formula);
				let user_id = this.user_id;
				let is_top = 0;
				let private_formula_id = this.private_formula_id;
				
				let formula_len = this.formula_len;
				formula_len = util.restrReplace(formula_len);
				
				let formula_degree = this.formula_degree;
				formula_degree = util.restrReplace(formula_degree);
				
				let name = val;
				setFormula({
					formula:formula,
					user_id:user_id,
					is_top:is_top,
					private_formula_id:private_formula_id,
					formula_len:formula_len,
					formula_degree:formula_degree,
					name:name,
					hash:hash,
					timestamp:timestamp,
					}).then(res=>{
					console.log("sssssssssss");
					if(res.code == '200'){
						uni.showToast({
							title: "保存成功",
							 duration: 2000,//提示的延迟时间，单位毫秒，默认：1500
						})
						// uni.showToast({
						// 	title: '更新成功',//标题 必填
						// 	icon: 'none',//图标
						//     mask: false,//是否显示透明蒙层，防止触摸穿透，默认：false
						//     duration: 2000,//提示的延迟时间，单位毫秒，默认：1500
						// });
						uni.setStorageSync('formula',JSON.stringify(res.data.private_formula));
						uni.$emit('back', 13)
								
						// 跳转回上一页
						setTimeout(function () {
							uni.switchTab({
								url:'/pages/index/formulalist'
							});
							// 返回时传递数据
							// uni.navigateBack({
							// 	delta: 1,
							// 	success: () => {
							// 	  uni.$emit('back', 12)
							// 	}
							// })
						}, 2000);
					}else{
						uni.showToast({
							title: res.msg,//标题 必填
							icon: 'none',//图标
						    mask: false,//是否显示透明蒙层，防止触摸穿透，默认：false
						    duration: 2000,//提示的延迟时间，单位毫秒，默认：1500
						});
						return
					}
				}).catch(
					(response) => {
						uni.showToast({
							title: "系统错误"+response.message,//标题 必填
							icon: 'none',//图标
						    mask: false,//是否显示透明蒙层，防止触摸穿透，默认：false
						    duration: 2000,//提示的延迟时间，单位毫秒，默认：1500
						});
					}
				)
			},
		}
	}
</script>

<style scoped lang="scss">
.btnshap{
	height: 19%;
	width: 19%;
	border-radius: 10rpx;
	// margin: 10rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	.text {
		text-align: center;
	}
}
.layout {
	box-sizing: border-box;
	width: 100%;
	height: 100%;
	padding: 0 20rpx;
	background-color: #111111;
	position: absolute;
	display: flex;
	flex-direction: column;
	justify-content: flex-end;
	.input-display: {
		width: 100%;
		height: 55%;
		color: #fff !important;
		
		// .text {
		// 	color: #fff;
		// }
	}
	.btn-group {
		margin: 40rpx 0;
		width: 100%;
		height: 45%;
		// background-color: #fff;
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
		:last-child {
			width: calc(100% - 40%);
		}
	}
}
</style>
